/**
 * Created by Administrator on 2017/8/1.
 */
import axios from 'axios';
import store from '../store/store'
import * as types from '../store/types'

const service = axios.create();


service.interceptors.request.use(config => {
  // 判断是否存在token，如果存在的话，则每个http header都加上token
  if (store.state.token) {
    config.headers.Authorization = `token ${store.state.token}`;
  }
  return config;
}, error => {
  console.log(error);
  Promise.reject(types.BEFORE_REQ_ERROR_CODE);
});

service.interceptors.response.use(
  response => {
    console.log(response);
    return response.data;
  },
  error => {
    console.log(error.response.data);
    return Promise.reject(error.response);
  });

/*service.interceptors.response.use(
  response => {
    console.log(response);
    //统一处理业务异常
    let code = null;

    //區分批處理
    if(_.isArray(response.data)){
      code = response.data.every(item=>{
        return _.isObject(item.state)&&item.state.code===types.RES_BASE_SUCCESS_CODE;
      })?types.RES_BATCH_SUCCESS_CODE:types.RES_BATCH_ERROR_CODE;
    }else{
      code = _.isObject(response.data.state)?response.data.state.code:types.UNKNOWN_RES_ERROR_CODE;
    }

    let promise = null;
    switch (code){
      case types.RES_BATCH_SUCCESS_CODE:
        //批处理成功
        promise = Promise.resolve(response.data);
        break;
      case types.RES_BASE_SUCCESS_CODE:
        //訪問成功
        promise = Promise.resolve(response.data.body);
        break;
      case types.RES_BASE_ERROR_CODE:
        //訪問錯誤
        promise = Promise.reject(response.data);
        break;
      case types.RES_UNLOGIN_ERROR_CODE:
        //未登錄
        store.commit(types.LOGOUT);
        promise = Promise.reject(response.data);
        break;
      case types.RES_PERMISSION_ERROR_CODE:
        //無權限
        promise = Promise.reject(response.data);
        break;
      case types.RES_BATCH_ERROR_CODE:
        //批處理異常
        promise = Promise.reject(response.data);
        break;
      default:
        //未知異常
        promise = Promise.reject(response.data);
    }
    return promise;
  },
  error => {
    console.log(error.response.data);
    return Promise.reject(error.response);
  }
);*/
export default service;
